from django.shortcuts import render, HttpResponse, redirect
from app01.utils.form import LoginForm
from app01 import models
from app01.utils.code import check_code
# 将图片写入内存
from io import BytesIO


def image_code(request):
    """生成图片验证码"""
    # 调用生成图片函数
    img, code_string = check_code()
    # print(code_string)

    # 将随机验证码写入session中，便于后续校验
    request.session['image_code'] = code_string
    # 给session设置60s超时,超时则验证码无效
    request.session.set_expiry(60)

    # 将图片对象img写入内存
    stream = BytesIO()
    img.save(stream, 'png')
    return HttpResponse(stream.getvalue())


def login(request):
    """登录"""
    if request.method == "GET":
        form = LoginForm()
        return render(request, 'login.html', {'form': form})

    form = LoginForm(data=request.POST)
    if form.is_valid():
        # print(form.cleaned_data)
        # {'username': '111', 'password': '111','code':111}
        # {'username': '111', 'password': '70a53ebb8836a4400fe2827ab6cc86bf','code':'xxx' }

        # 验证码校验
        # user_input_code = form.cleaned_data["code"]
        # 获取用户输入的验证码并从数据字典中拿掉，防止影响下面的用户验证
        user_input_code = form.cleaned_data.pop("code")
        code = request.session.get('image_code', '')  # 如果验证码超时则返回空
        if code.upper() != user_input_code.upper():
            form.add_error("code", "验证码错误")
            return render(request, 'login.html', {'form': form})

        # 去数据库进行校验，获取用户对象、None
        # admin_object = models.Admin.objects.filter(username=form.cleaned_data['username'],password=form.cleaned_data['password']).first()
        admin_object = models.Admin.objects.filter(**form.cleaned_data).first()
        # 用户名为空
        if not admin_object:
            form.add_error("password", "用户名或密码错误")
            return render(request, 'login.html', {'form': form})
        # 用户名和密码正确
        # 网站随机生成字符串，写到用户浏览器的cookie中，在写入到session中
        request.session["info"] = {'id': admin_object.id, 'name': admin_object.username}
        # 登录之后重新设置session验证时间，实现七天免登陆（不重新设置的话会按照原来的验证码每隔60s就要重新登录一次）
        request.session.set_expiry(60 * 60 * 24 * 7)
        return redirect("/admin/list/")
    return render(request, 'login.html', {'form': form})


def logout(request):
    """注销"""
    request.session.clear()
    return redirect("/login/")
